package com.dfl.gankio

import android.app.Application
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

/**
 * A creator is used to inject the product ID into the ViewModel
 *
 * This creator is to showcase how to inject dependencies into ViewModels.
 */
class ViewModelFactory : ViewModelProvider.NewInstanceFactory() {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        try {
            //反射初始化ViewModel
            return Class.forName(modelClass.name).newInstance() as T
        } catch (e: InstantiationException) {
            throw  RuntimeException("Cannot create an instance of $modelClass", e)
        } catch (e: IllegalAccessException) {
            throw  RuntimeException("Cannot create an instance of $modelClass", e)
        }
    }

    companion object {
        fun newInstance() = ViewModelFactory()
    }
}
